package com.patrick.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {

    public static void main(String[] args) {

//        处理连接的线程池
        EventLoopGroup acceptGroup = new NioEventLoopGroup();

//        处理数据的线程池
        EventLoopGroup readGroup = new NioEventLoopGroup();


        ServerBootstrap b = new ServerBootstrap();
        b.group(acceptGroup, readGroup);
        b.channel(NioServerSocketChannel.class);
//        职责链定义（请求交给谁去处理）
        b.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();

                pipeline.addLast(new Decoder());

                pipeline.addLast(new Handler());
            }
        });

        try {
            b.bind(8080).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            acceptGroup.shutdownGracefully();
            readGroup.shutdownGracefully();
        }

    }
}
